package usbcali.edu.presentation.backEndBeans;

import com.icesoft.faces.async.render.RenderManager;
import com.icesoft.faces.async.render.Renderable;
import com.icesoft.faces.component.ext.HtmlCommandButton;
import com.icesoft.faces.component.ext.HtmlInputText;
import com.icesoft.faces.component.selectinputdate.SelectInputDate;
import com.icesoft.faces.context.DisposableBean;
import com.icesoft.faces.webapp.xmlhttp.FatalRenderingException;
import com.icesoft.faces.webapp.xmlhttp.PersistentFacesState;
import com.icesoft.faces.webapp.xmlhttp.RenderingException;
import com.icesoft.faces.webapp.xmlhttp.TransientRenderingException;



import usbcali.edu.exceptions.*;

import usbcali.edu.persistencia.*;
import usbcali.edu.persistencia.dto.HorarioRxsalaDTO;

import usbcali.edu.presentation.businessDelegate.BusinessDelegatorView;

import usbcali.edu.utilities.*;

import java.math.BigDecimal;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.TimeZone;
import java.util.Vector;

import javax.faces.event.ValueChangeEvent;
import javax.faces.model.DataModel;


/**
*
*
* @author Zathura Code Generator http://code.google.com/p/zathura
*
*/
public class HorarioRxsalaView extends DataSource implements Renderable,
    DisposableBean {
    private HtmlInputText txtCodReservas_Reservas;
    private HtmlInputText txtCodSala_Salas;
    private HtmlInputText txtCodReservas;
    private HtmlInputText txtConsecutivo;
    private HtmlInputText txtCodSala;
    private SelectInputDate txtFechaEvento;
    private HtmlCommandButton btnSave;
    private HtmlCommandButton btnModify;
    private HtmlCommandButton btnDelete;
    private HtmlCommandButton btnClear;
    private boolean renderDataTable;
    private boolean flag = true;
    private RenderManager renderManager;
    private PersistentFacesState state = PersistentFacesState.getInstance();
    private List<HorarioRxsala> horarioRxsala;
    private List<HorarioRxsalaDTO> horarioRxsalaDTO;

    public HorarioRxsalaView() {
        super("");
    }

    public String action_clear() {
        txtCodReservas_Reservas.setValue(null);
        txtCodReservas_Reservas.setDisabled(true);
        txtCodSala_Salas.setValue(null);
        txtCodSala_Salas.setDisabled(true);
        txtCodReservas.setValue(null);
        txtCodReservas.setDisabled(false);
        txtConsecutivo.setValue(null);
        txtConsecutivo.setDisabled(false);
        txtCodSala.setValue(null);
        txtCodSala.setDisabled(false);
        txtFechaEvento.setValue(null);
        txtFechaEvento.setDisabled(false);
        btnSave.setDisabled(true);
        btnDelete.setDisabled(true);
        btnModify.setDisabled(true);
        btnClear.setDisabled(false);

        return "";
    }

    public void listener_txtId(ValueChangeEvent event) {
        if ((event.getNewValue() != null) && !event.getNewValue().equals("")) {
            HorarioRxsala entity = null;

            try {
                HorarioRxsalaId id = new HorarioRxsalaId();
                id.setCodReservas((((txtCodReservas.getValue()) == null) ||
                    (txtCodReservas.getValue()).equals("")) ? null
                                                            : new String(
                        txtCodReservas.getValue().toString()));
                id.setConsecutivo((((txtConsecutivo.getValue()) == null) ||
                    (txtConsecutivo.getValue()).equals("")) ? null
                                                            : new String(
                        txtConsecutivo.getValue().toString()));
                id.setCodSala((((txtCodSala.getValue()) == null) ||
                    (txtCodSala.getValue()).equals("")) ? null
                                                        : new String(
                        txtCodSala.getValue().toString()));
                id.setFechaEvento((((txtFechaEvento.getValue()) == null) ||
                    (txtFechaEvento.getValue()).equals("")) ? null
                                                            : (Date) txtFechaEvento.getValue());
                entity = BusinessDelegatorView.getHorarioRxsala(id);
            } catch (Exception e) {
                // TODO: handle exception
            }

            if (entity == null) {
                txtCodReservas_Reservas.setDisabled(false);
                txtCodSala_Salas.setDisabled(false);
                txtCodReservas.setDisabled(false);
                txtConsecutivo.setDisabled(false);
                txtCodSala.setDisabled(false);
                txtFechaEvento.setDisabled(false);
                btnSave.setDisabled(false);
                btnDelete.setDisabled(true);
                btnModify.setDisabled(true);
                btnClear.setDisabled(false);
            } else {
                txtCodReservas_Reservas.setValue(entity.getReservas()
                                                       .getCodReservas());
                txtCodReservas_Reservas.setDisabled(false);
                txtCodSala_Salas.setValue(entity.getSalas().getCodSala());
                txtCodSala_Salas.setDisabled(false);
                txtCodReservas.setValue(entity.getId().getCodReservas());
                txtCodReservas.setDisabled(true);
                txtConsecutivo.setValue(entity.getId().getConsecutivo());
                txtConsecutivo.setDisabled(true);
                txtCodSala.setValue(entity.getId().getCodSala());
                txtCodSala.setDisabled(true);
                txtFechaEvento.setValue(entity.getId().getFechaEvento());
                txtFechaEvento.setDisabled(true);
                btnSave.setDisabled(true);
                btnDelete.setDisabled(false);
                btnModify.setDisabled(false);
                btnClear.setDisabled(false);
            }
        }
    }

    public String action_save() {
        try {
        	 BusinessDelegatorView.saveHorarioRxsala(FacesUtils.checkString(
                     txtCodReservas), FacesUtils.checkString(txtConsecutivo),
                 FacesUtils.checkBigDecimal(txtCodSala),
                 FacesUtils.checkDate(txtFechaEvento)
                );
            FacesUtils.addInfoMessage(ZMessManager.ENTITY_SUCCESFULLYSAVED);
            action_clear();
        } catch (Exception e) {
            FacesUtils.addErrorMessage(e.getMessage());
        }

        return "";
    }

    public String action_delete() {
        try {
            BusinessDelegatorView.deleteHorarioRxsala(FacesUtils.checkString(
                    txtCodReservas), FacesUtils.checkString(txtConsecutivo),
                FacesUtils.checkString(txtCodSala),
                FacesUtils.checkDate(txtFechaEvento));
            FacesUtils.addInfoMessage(ZMessManager.ENTITY_SUCCESFULLYDELETED);
            action_clear();
        } catch (Exception e) {
            FacesUtils.addErrorMessage(e.getMessage());
        }

        return "";
    }

    public String action_modify() {
        try {
            BusinessDelegatorView.updateHorarioRxsala(FacesUtils.checkString(
                    txtCodReservas), FacesUtils.checkString(txtConsecutivo),
                FacesUtils.checkString(txtCodSala),
                FacesUtils.checkDate(txtFechaEvento),
                FacesUtils.checkString(txtCodReservas_Reservas),
                FacesUtils.checkString(txtCodSala_Salas));
            FacesUtils.addInfoMessage(ZMessManager.ENTITY_SUCCESFULLYMODIFIED);
            action_clear();
        } catch (Exception e) {
            FacesUtils.addErrorMessage(e.getMessage());
        }

        return "";
    }

    public String action_modifyWitDTO(String codReservas, String consecutivo,
        String codSala, Date fechaEvento, String codReservas_Reservas,
        String codSala_Salas) throws Exception {
        try {
            BusinessDelegatorView.updateHorarioRxsala(codReservas, consecutivo,
                codSala, fechaEvento, codReservas_Reservas, codSala_Salas);
            renderManager.getOnDemandRenderer("HorarioRxsalaView")
                         .requestRender();
            FacesUtils.addInfoMessage(ZMessManager.ENTITY_SUCCESFULLYMODIFIED);
        } catch (Exception e) {
            //renderManager.getOnDemandRenderer("HorarioRxsalaView").requestRender();
            FacesUtils.addErrorMessage(e.getMessage());
            throw e;
        }

        return "";
    }

    public List<HorarioRxsala> getHorarioRxsala() {
        if (flag) {
            try {
                horarioRxsala = BusinessDelegatorView.getHorarioRxsala();
                flag = false;
            } catch (Exception e) {
                flag = true;
                FacesUtils.addErrorMessage(e.getMessage());
            }
        }

        return horarioRxsala;
    }

    public boolean isFlag() {
        return flag;
    }

    public void setHorarioRxsala(List<HorarioRxsala> horarioRxsala) {
        this.horarioRxsala = horarioRxsala;
    }

    public boolean isRenderDataTable() {
        try {
            if (flag) {
                if (BusinessDelegatorView.findTotalNumberHorarioRxsala() > 0) {
                    renderDataTable = true;
                } else {
                    renderDataTable = false;
                }
            }

            flag = false;
        } catch (Exception e) {
            renderDataTable = false;
            e.printStackTrace();
        }

        return renderDataTable;
    }

    public DataModel getData() {
        state = PersistentFacesState.getInstance();

        if (onePageDataModel == null) {
            onePageDataModel = new LocalDataModel(pageSize);
        }

        return onePageDataModel;
    }

    /**
    * This is where the Object data is retrieved from the database and
    * returned as a list of objects for display in the UI.
    */
    private DataPage<HorarioRxsala> getDataPage(int startRow, int pageSize) {
        // Retrieve the total number of objects from the database.  This
        // number is required by the DataPage object so the paginator will know
        // the relative location of the page data.
        int totalNumberHorarioRxsala = 0;

        try {
            totalNumberHorarioRxsala = BusinessDelegatorView.findTotalNumberHorarioRxsala()
                                                            .intValue();
        } catch (Exception e) {
            FacesUtils.addErrorMessage(e.getMessage());
        }

        // Calculate indices to be displayed in the ui.
        int endIndex = startRow + pageSize;

        if (endIndex > totalNumberHorarioRxsala) {
            endIndex = totalNumberHorarioRxsala;
        }

        try {
            horarioRxsala = BusinessDelegatorView.findPageHorarioRxsala(sortColumnName,
                    sortAscending, startRow, endIndex - startRow);

            // Remove this Renderable from the existing render groups.
            //leaveRenderGroups();        			
        } catch (Exception e) {
            FacesUtils.addErrorMessage(e.getMessage());
        }

        // Add this Renderable to the new render groups.
        //joinRenderGroups();
        // Reset the dirtyData flag.
        onePageDataModel.setDirtyData(false);
        // This is required when using Hibernate.  If the SessionManager is not
        // cleared or closed objects are cached and stale objects will show up
        // in the table.
        // This way, the detached objects are reread from the database.
        // This call is not required with Hibernate, which uses a Query Hint
        // to clear the l2 cache in the DAO.
        flag = true;

        return new DataPage<HorarioRxsala>(totalNumberHorarioRxsala, startRow,
            horarioRxsala);
    }

    public DataModel getDataDTO() {
        state = PersistentFacesState.getInstance();

        if (onePageDataModel == null) {
            onePageDataModel = new LocalDataModelDTO(pageSize);
        }

        return onePageDataModel;
    }

    /**
    * This is where the Object data is retrieved from the database and
    * returned as a list of objects for display in the UI.
    */
    private DataPage<HorarioRxsalaDTO> getDataPageDTO(int startRow, int pageSize) {
        // Retrieve the total number of objects from the database.  This
        // number is required by the DataPage object so the paginator will know
        // the relative location of the page data.
        int totalNumberHorarioRxsala = 0;

        try {
            totalNumberHorarioRxsala = BusinessDelegatorView.findTotalNumberHorarioRxsala()
                                                            .intValue();
        } catch (Exception e) {
            FacesUtils.addErrorMessage(e.getMessage());
        }

        // Calculate indices to be displayed in the ui.
        int endIndex = startRow + pageSize;

        if (endIndex > totalNumberHorarioRxsala) {
            endIndex = totalNumberHorarioRxsala;
        }

        try {
            horarioRxsala = BusinessDelegatorView.findPageHorarioRxsala(sortColumnName,
                    sortAscending, startRow, endIndex - startRow);

            if (Utilities.validationsList(horarioRxsala)) {
                horarioRxsalaDTO = new ArrayList<HorarioRxsalaDTO>();

                for (HorarioRxsala horarioRxsalaTmp : horarioRxsala) {
                    HorarioRxsalaDTO horarioRxsalaDTO2 = new HorarioRxsalaDTO();
                    horarioRxsalaDTO2.setCodReservas(horarioRxsalaTmp.getId()
                                                                     .getCodReservas()
                                                                     .toString());
                    horarioRxsalaDTO2.setConsecutivo(horarioRxsalaTmp.getId()
                                                                     .getConsecutivo()
                                                                     .toString());
                    horarioRxsalaDTO2.setCodSala(horarioRxsalaTmp.getId()
                                                                 .getCodSala()
                                                                 .toString());
                    horarioRxsalaDTO2.setFechaEvento(horarioRxsalaTmp.getId()
                                                                     .getFechaEvento());
                    horarioRxsalaDTO2.setCodReservas_Reservas((horarioRxsalaTmp.getReservas()
                                                                               .getCodReservas() != null)
                        ? horarioRxsalaTmp.getReservas().getCodReservas()
                                          .toString() : null);
                    horarioRxsalaDTO2.setCodSala_Salas((horarioRxsalaTmp.getSalas()
                                                                        .getCodSala() != null)
                        ? horarioRxsalaTmp.getSalas().getCodSala().toString()
                        : null);
                    horarioRxsalaDTO2.setHorarioRxsala(horarioRxsalaTmp);
                    horarioRxsalaDTO2.setHorarioRxsalaView(this);
                    horarioRxsalaDTO.add(horarioRxsalaDTO2);
                }
            }

            // Remove this Renderable from the existing render groups.
            leaveRenderGroups();
        } catch (Exception e) {
            FacesUtils.addErrorMessage(e.getMessage());
        }

        // Add this Renderable to the new render groups.
        joinRenderGroups();
        // Reset the dirtyData flag.
        onePageDataModel.setDirtyData(false);
        // This is required when using Hibernate.  If the SessionManager is not
        // cleared or closed objects are cached and stale objects will show up
        // in the table.
        // This way, the detached objects are reread from the database.
        // This call is not required with Hibernate, which uses a Query Hint
        // to clear the l2 cache in the DAO.
        flag = true;

        return new DataPage<HorarioRxsalaDTO>(totalNumberHorarioRxsala,
            startRow, horarioRxsalaDTO);
    }

    protected boolean isDefaultAscending(String sortColumn) {
        return true;
    }

    /**
    * This method is called when a render call is made from the server. Render
    * calls are only made to views containing an updated record. The data is
    * marked as dirty to trigger a fetch of the updated record from the
    * database before rendering takes place.
    */
    public PersistentFacesState getState() {
        onePageDataModel.setDirtyData();

        return state;
    }

    /**
    * This method is called from faces-config.xml with each new session.
    */
    public void setRenderManager(RenderManager renderManager) {
        this.renderManager = renderManager;
    }

    public void renderingException(RenderingException arg0) {
        if (arg0 instanceof TransientRenderingException) {
        } else if (arg0 instanceof FatalRenderingException) {
            // Remove from existing Customer render groups.
            leaveRenderGroups();
        }
    }

    /**
    * Remove this Renderable from existing uiCustomerBeans render groups.
    * OnDemandRenderers are named/created using the underlying Customer Number.
    */
    private void leaveRenderGroups() {
        if (Utilities.validationsList(horarioRxsalaDTO)) {
            for (HorarioRxsalaDTO horarioRxsalaTmp : horarioRxsalaDTO) {
                renderManager.getOnDemandRenderer("HorarioRxsalaView")
                             .remove(this);
            }
        }
    }

    /**
    * Add this Renderable to the new uiCustomerBeans render groups.
    * OnDemandRenderers are named/created using the underlying Customer Number.
    */
    private void joinRenderGroups() {
        if (Utilities.validationsList(horarioRxsalaDTO)) {
            for (HorarioRxsalaDTO horarioRxsalaTmp : horarioRxsalaDTO) {
                renderManager.getOnDemandRenderer("HorarioRxsalaView").add(this);
            }
        }
    }

    public void dispose() throws Exception {
    }

    public RenderManager getRenderManager() {
        return renderManager;
    }

    public void setState(PersistentFacesState state) {
        this.state = state;
    }

    public HtmlInputText getTxtCodReservas_Reservas() {
        return txtCodReservas_Reservas;
    }

    public void setTxtCodReservas_Reservas(
        HtmlInputText txtCodReservas_Reservas) {
        this.txtCodReservas_Reservas = txtCodReservas_Reservas;
    }

    public HtmlInputText getTxtCodSala_Salas() {
        return txtCodSala_Salas;
    }

    public void setTxtCodSala_Salas(HtmlInputText txtCodSala_Salas) {
        this.txtCodSala_Salas = txtCodSala_Salas;
    }

    public HtmlInputText getTxtCodReservas() {
        return txtCodReservas;
    }

    public void setTxtCodReservas(HtmlInputText txtCodReservas) {
        this.txtCodReservas = txtCodReservas;
    }

    public HtmlInputText getTxtConsecutivo() {
        return txtConsecutivo;
    }

    public void setTxtConsecutivo(HtmlInputText txtConsecutivo) {
        this.txtConsecutivo = txtConsecutivo;
    }

    public HtmlInputText getTxtCodSala() {
        return txtCodSala;
    }

    public void setTxtCodSala(HtmlInputText txtCodSala) {
        this.txtCodSala = txtCodSala;
    }

    public SelectInputDate getTxtFechaEvento() {
        return txtFechaEvento;
    }

    public void setTxtFechaEvento(SelectInputDate txtFechaEvento) {
        this.txtFechaEvento = txtFechaEvento;
    }

    public HtmlCommandButton getBtnSave() {
        return btnSave;
    }

    public void setBtnSave(HtmlCommandButton btnSave) {
        this.btnSave = btnSave;
    }

    public HtmlCommandButton getBtnModify() {
        return btnModify;
    }

    public void setBtnModify(HtmlCommandButton btnModify) {
        this.btnModify = btnModify;
    }

    public HtmlCommandButton getBtnDelete() {
        return btnDelete;
    }

    public void setBtnDelete(HtmlCommandButton btnDelete) {
        this.btnDelete = btnDelete;
    }

    public HtmlCommandButton getBtnClear() {
        return btnClear;
    }

    public void setBtnClear(HtmlCommandButton btnClear) {
        this.btnClear = btnClear;
    }

    public void setRenderDataTable(boolean renderDataTable) {
        this.renderDataTable = renderDataTable;
    }

    public void setFlag(boolean flag) {
        this.flag = flag;
    }

    public List<HorarioRxsalaDTO> getHorarioRxsalaDTO() {
        return horarioRxsalaDTO;
    }

    public void setHorarioRxsalaDTO(List<HorarioRxsalaDTO> horarioRxsalaDTO) {
        this.horarioRxsalaDTO = horarioRxsalaDTO;
    }

    public TimeZone getTimeZone() {
        return java.util.TimeZone.getDefault();
    }

    /**
    * A special type of JSF DataModel to allow a datatable and datapaginator
    * to page through a large set of data without having to hold the entire
    * set of data in memory at once.
    * Any time a managed bean wants to avoid holding an entire dataset,
    * the managed bean declares this inner class which extends PagedListDataModel
    * and implements the fetchData method. fetchData is called
    * as needed when the table requires data that isn't available in the
    * current data page held by this object.
    * This requires the managed bean (and in general the business
    * method that the managed bean uses) to provide the data wrapped in
    * a DataPage object that provides info on the full size of the dataset.
    */
    private class LocalDataModel extends PagedListDataModel {
        public LocalDataModel(int pageSize) {
            super(pageSize);
        }

        public DataPage<HorarioRxsala> fetchPage(int startRow, int pageSize) {
            // call enclosing managed bean method to fetch the data
            return getDataPage(startRow, pageSize);
        }
    }

    private class LocalDataModelDTO extends PagedListDataModel {
        public LocalDataModelDTO(int pageSize) {
            super(pageSize);
        }

        public DataPage<HorarioRxsalaDTO> fetchPage(int startRow, int pageSize) {
            // call enclosing managed bean method to fetch the data
            return getDataPageDTO(startRow, pageSize);
        }
    }
}
